import echarts from 'echarts';
import { ARCGIS_JS_API_URL } from '../common/constants';
import { loadModules } from 'esri-loader';
import h337 from 'heatmapjs'
import { ARCGIS_RELATED_PLUGINS_URL } from '../common/constants';
import drawRegionCity from '../assets/geojson/draw_region_city.json';
import drawRegionProvince from '../assets/geojson/draw_region_province.json';
import dataPOI from '../assets/test/dataPOI.json';
import city_basic_info from '../assets/datajson/city_basic_info.json';
import city_relation_radardata from '../assets/datajson/city_relation_radardata.json';

// 高亮
var highlight;

export function createAllRegionPointsAndPolygons() {
  loadModules(['esri/Graphic', 'esri/geometry/Point', 'esri/geometry/Polygon'], {
    url: ARCGIS_JS_API_URL,
  }).then(([Graphic, Point, Polygon]) => {
    //POLYGON
    window['ALL_CITY_POLYGON_GRAPHICS'] = [];
    window['ALL_PROVINCE_POLYGON_GRAPHICS'] = [];
    window['ALL_CITY_POINT_GRAPHICS'] = [];
    window['ALL_PROVINCE_POINT_GRAPHICS'] = [];
    window['ALL_CITY_COORMAP'] = {};
    // let idx=0
    drawRegionCity.features.map(item => {
      const rings = item.geometry.rings;
      const polygon = new Polygon({
        hasZ: false,
        hasM: false,
        rings: rings,
        spatialReference: { wkid: 4326 },
      });
      const polygonGraphic = new Graphic({
        geometry: polygon,
        attributes: item.attributes,
      });
      window['ALL_CITY_POLYGON_GRAPHICS'].push(polygonGraphic);
      const point = new Point({
        // 几何中心
        // x: item.attributes.x,
        // y: item.attributes.y,
        // 行政中心
        x: item.attributes.city_x,
        y: item.attributes.city_y,
        spatialReference: { wkid: 4326 },
      });
      const pointGraphic = new Graphic({
        geometry: point,
        attributes: item.attributes,
      });
      window['ALL_CITY_POINT_GRAPHICS'].push(pointGraphic);
      window['ALL_CITY_COORMAP'][item.attributes.cn_name] = [item.attributes.city_x, item.attributes.city_y];
    });
    drawRegionProvince.features.map(item => {
      const rings = item.geometry.rings;
      const polygon = new Polygon({
        hasZ: false,
        hasM: false,
        rings: rings,
        spatialReference: { wkid: 4326 },
      });
      const polygonGraphic = new Graphic({
        geometry: polygon,
        attributes: item.attributes,
      });
      window['ALL_PROVINCE_POLYGON_GRAPHICS'].push(polygonGraphic);
      const point = new Point({
        // 几何中心
        x: item.attributes.x,
        y: item.attributes.y,
        // 行政中心
        // x: item.attributes.city_x,
        // y: item.attributes.city_y,
        spatialReference: { wkid: 4326 },
      });
      const pointGraphic = new Graphic({
        geometry: point,
        attributes: item.attributes,
      });
      window['ALL_PROVINCE_POINT_GRAPHICS'].push(pointGraphic);
    });
  });
}

export function openMigrateEchartsLayer(dataArray, that) {
  // TODO: 清空geojson图层
  that.setState({
    showDataChart: false,
  });

  loadModules(['userPlugins/Echarts4Layer'], {
    url: ARCGIS_JS_API_URL,
    dojoConfig: {
      async: true,
      // tlmSiblingOfDojo: false,
      packages: [
        {
          name: 'userPlugins',
          location: ARCGIS_RELATED_PLUGINS_URL,
          // location: location.pathname.replace(/\/[^/]+$/, '') + '/userPlugins',
        },
      ],
    },
  }).then(([Echarts4Layer]) => {
    var rendererData = [],
      inOrOut,
      lastObj;
    dataArray.map(item => {
      const obj = [{ name: item.cityFrom }, { name: item.cityTo, value: item.heat }];
      if (!inOrOut && lastObj) {
        item.cityFrom === lastObj.cityFrom ? (inOrOut = 'out') : (inOrOut = 'in');
      }
      lastObj = item;
      // const obj=[{name:item.cityTo},{name:item.cityFrom,value:item.heat}]
      // const obj={cityFrom:item.cityFrom,cityTo:item.cityFrom,value:item.heat};
      rendererData.push(obj);
    });
    console.log(inOrOut);

    // var planePath =
    //   'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z';
    var planePath = 'path://';
    var convertData = function (data) {
      var res = [];
      for (var i = 0; i < data.length; i++) {
        var dataItem = data[i];
        var fromCoord = window['ALL_CITY_COORMAP'][dataItem[0].name];
        var toCoord = window['ALL_CITY_COORMAP'][dataItem[1].name];
        if (fromCoord && toCoord) {
          res.push({
            fromName: dataItem[0].name,
            toName: dataItem[1].name,
            coords: [fromCoord, toCoord],
            value: dataItem[1].value,
          });
        }
      }
      return res;
    };
    var color = ['#a6c84c', '#ffa022', '#46bee9', '#188df0'];
    // var color = ['#a6c84c'];
    var series = [];
    [['', rendererData]].forEach(function (item, i) {
      series.push(
        {
          name: item[0] + ' Top10',
          type: 'lines',
          coordinateSystem: 'arcgis',
          zlevel: 2,
          // symbol: ['none', 'arrow'],
          symbolSize: 10,
          edgeLabel: {
            normal: {
              show: true,
              textStyle: {
                fontSize: 14
              },
              // formatter: function(params) {
              //     let txt = ''
              //     if (params.data.speed !== undefined) {
              //         txt = params.data.speed
              //     }
              //     return txt
              // },
            }
          },
          effect: {
            show: true,
            period: 2, //箭头指向速度，值越小速度越快
            trailLength: 0.02, //特效尾迹长度[0,1]值越大，尾迹越长重
            symbol: 'arrow', //箭头图标
            symbolSize: 5, //图标大小
          },
          lineStyle: {
            normal: {
              color: color[i],
              width: 1, //尾迹线条宽度
              opacity: 1, //尾迹线条透明度
              curveness: .3 //尾迹线条曲直度
            }
          },
          data: convertData(item[1]),
        },
        {
          name: item[0] + ' Top10',
          type: 'effectScatter',
          coordinateSystem: 'arcgis',
          zlevel: 2,
          rippleEffect: { //涟漪特效
            period: 4, //动画时间，值越小速度越快
            brushType: 'stroke', //波纹绘制方式 stroke, fill
            scale: 4 //波纹圆环最大限制，值越大波纹越大
          },
          label: {
            normal: {
              show: true,
              position: 'right',
              formatter: '{b}',
            },
          },
          symbolSize: function (val) {
            return val[2];
          },
          itemStyle: {
            normal: {
              color: color[i],
            },
          },
          data: item[1].map(function (dataItem) {
            return {
              name: inOrOut === 'in' ? dataItem[0].name : dataItem[1].name,
              value: window['ALL_CITY_COORMAP'][inOrOut === 'in' ? dataItem[0].name : dataItem[1].name].concat([
                dataItem[1].value,
              ]),
            };
          }),
        }
      );
    });
    window['Echarts4Layer'] = new Echarts4Layer(window['CSJ_SCENE_VIEW'], echarts);
    var option = {
      series: series,
      visualMap: [
        {
          show: false,
          min: 5,
          max: 25,
          color: ['#ff3333', 'orange', 'yellow', 'lime', 'aqua'],
        }]
    };
    window['Echarts4Layer'].setChartOption(option);
  });
}

export function openRelationEchartsLayer(dataArray, that) {
  that.setState({
    showDataChart: false,
  });
  loadModules(['userPlugins/Echarts4Layer'], {
    url: ARCGIS_JS_API_URL,
    dojoConfig: {
      async: true,
      packages: [
        {
          name: 'userPlugins',
          location: ARCGIS_RELATED_PLUGINS_URL,
        },
      ],
    },
  }).then(([Echarts4Layer]) => {
    var data1 = [
      [{
        name: '上海'
      }, {
        name: '苏州',
        value: 53223
      }],
      [{
        name: '苏州'
      }, {
        name: '上海',
        value: 72806
      }],
      [{
        name: '苏州'
      }, {
        name: '无锡',
        value: 28926
      }],
      [{
        name: '无锡'
      }, {
        name: '常州',
        value: 16423
      }],
      [{
        name: '常州'
      }, {
        name: '南京',
        value: 32073
      }],
      [{
        name: '南京'
      }, {
        name: '合肥',
        value: 21469
      }],
      [{
        name: '上海'
      }, {
        name: '宁波',
        value: 36993
      },
      ],
      [{
        name: '宁波'
      }, {
        name: '台州',
        value: 19143
      },
      ],
      [{
        name: '台州'
      }, {
        name: '温州',
        value: 29511
      },
      ],
      [{
        name: '上海'
      }, {
        name: '南通',
        value: 19057
      }
      ],
      [{
        name: '南通'
      }, {
        name: '盐城',
        value: 10017
      }],
      [{
        name: '盐城'
      }, {
        name: '连云港',
        value: 6311
      }],
      [{
        name: '上海'
      }, {
        name: '嘉兴',
        value: 18244
      }
      ],
      [{
        name: '嘉兴'
      }, {
        name: '杭州',
        value: 42227
      }
      ],
      [{
        name: '杭州'
      }, {
        name: '金华',
        value: 4146
      }
      ],
    ];
    // var planePath =
    //   'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z';
    var planePath = 'path://';
    var convertData = function (data) {
      var res = [];
      for (var i = 0; i < data.length; i++) {
        var dataItem = data[i];
        var fromCoord = window['ALL_CITY_COORMAP'][dataItem[0].name];
        var toCoord = window['ALL_CITY_COORMAP'][dataItem[1].name];
        if (fromCoord && toCoord) {
          res.push([{
            coord: fromCoord,
          }, {
            coord: toCoord,
            value: dataItem[1].value //线条颜色
          }]);
        }
      }
      return res;
    };

    var series = [];
    [data1].forEach(function (item, i) {
      series.push({
        name: '1',
        type: 'lines',
        coordinateSystem: 'arcgis',
        zlevel: 2,
        lineStyle: {
          normal: {
            width: 6,
            // curveness: 0.1, //弧线角度
            opacity: 0.6,
            color: 'yellow'
          }
        },
        data: convertData(item)
      }, {
        name: '2',
        type: 'lines',
        coordinateSystem: 'arcgis',
        zlevel: 2,
        lineStyle: {
          normal: {
            width: 20,
            // curveness: 0.1, //弧线角度
            opacity: 0.3,
            color: 'yellow'
          }
        },
        data: convertData(item)
      },
        {
          type: 'effectScatter',
          coordinateSystem: 'arcgis',
          zlevel: 2,
          //波纹效果
          rippleEffect: {
            period: 2,
            brushType: 'stroke',
            scale: 3
          },
          label: {
            normal: {
              show: true,
              position: 'bottom',
              formatter: '{b}',
              color: 'yellow'
            }
          },
          //终点形象
          symbol: 'circle',
          //圆点大小
          symbolSize: function (val) {
            return val[2] / 2000;
          },
          itemStyle: {
            normal: {
              show: true
            }
          },
          data: item.map(function (dataItem) {
            return {
              name: dataItem[1].name,
              value: window['ALL_CITY_COORMAP'][dataItem[1].name].concat([dataItem[1].value])
            };
          })
        }
      );
    });
    window['Echarts4Layer'] = new Echarts4Layer(window['CSJ_SCENE_VIEW'], echarts);
    var option = {
      series: series,
      visualMap: [
        {
          show: false,
          min: 50000,
          max: 5000,
          color: ['#ff3333', 'orange', 'yellow', 'lime', 'aqua'],
        }]
    };
    window['Echarts4Layer'].setChartOption(option);
  });
}

export function openCityRelationEchartsLayer(dataArray, that) {
  that.setState({
    showDataChart: false,
  });

  loadModules(['userPlugins/Echarts4Layer'], {
    url: ARCGIS_JS_API_URL,
    dojoConfig: {
      async: true,
      packages: [
        {
          name: 'userPlugins',
          location: ARCGIS_RELATED_PLUGINS_URL,
        },
      ],
    },
  }).then(([Echarts4Layer]) => {
    var data1 = [
      [{
        name: '常州'
      }, {
        name: '南京',
        value: 25
      }],
      [{
        name: '常州'
      }, {
        name: '上海',
        value: 18
      }],
      [{
        name: '杭州'
      }, {
        name: '宁波',
        value: 18.5
      }],
      [{
        name: '杭州'
      }, {
        name: '上海',
        value: 25.8
      }],
      [{
        name: '杭州'
      }, {
        name: '绍兴',
        value: 23.19
      }],
      [{
        name: '合肥'
      }, {
        name: '上海',
        value: 18
      }],
      [{
        name: '湖州'
      }, {
        name: '杭州',
        value: 22.3
      },
      ],
      [{
        name: '嘉兴'
      }, {
        name: '杭州',
        value: 28.9
      },
      ],
      [{
        name: '金华'
      }, {
        name: '杭州',
        value: 27
      },
      ],
      [{
        name: '南京'
      }, {
        name: '常州',
        value: 19
      }],
      [{
        name: '南京'
      }, {
        name: '南通',
        value: 20
      },
      ],
      [{
        name: '南京'
      }, {
        name: '上海',
        value: 52
      },
      ],
      [{
        name: '南京'
      }, {
        name: '苏州',
        value: 47
      },
      ],
      [{
        name: '南京'
      }, {
        name: '无锡',
        value: 20.2
      }
      ],
      [{
        name: '南京'
      }, {
        name: '盐城',
        value: 16
      }],
      [{
        name: '南京'
      }, {
        name: '镇江',
        value: 27
      }],
      [{
        name: '南通'
      }, {
        name: '南京',
        value: 21
      }
      ],
      [{
        name: '南通'
      }, {
        name: '上海',
        value: 29
      }
      ],
      [{
        name: '宁波'
      }, {
        name: '上海',
        value: 19
      }
      ],

      [{
        name: '上海'
      }, {
        name: '杭州',
        value: 69
      }],
      [{
        name: '上海'
      }, {
        name: '合肥',
        value: 33
      },
      ],
      [{
        name: '上海'
      }, {
        name: '嘉兴',
        value: 37
      },
      ],
      [{
        name: '上海'
      }, {
        name: '金华',
        value: 24
      },
      ],
      [{
        name: '上海'
      }, {
        name: '南京',
        value: 46
      },
      ],
      [{
        name: '上海'
      }, {
        name: '南通',
        value: 29
      },
      ],
      [{
        name: '上海'
      }, {
        name: '宁波',
        value: 49
      },
      ],
      [{
        name: '上海'
      }, {
        name: '苏州',
        value: 100
      },
      ],
      [{
        name: '上海'
      }, {
        name: '台州',
        value: 21
      },
      ],
      [{
        name: '上海'
      }, {
        name: '无锡',
        value: 27
      },
      ],
      [{
        name: '苏州'
      }, {
        name: '南京',
        value: 34
      },
      ],
      [{
        name: '苏州'
      }, {
        name: '上海',
        value: 69
      },
      ],
      [{
        name: '苏州'
      }, {
        name: '无锡',
        value: 22
      },
      ],
      [{
        name: '无锡'
      }, {
        name: '南京',
        value: 24
      }
      ],
      [{
        name: '无锡'
      }, {
        name: '上海',
        value: 31
      }
      ],
      [{
        name: '无锡'
      }, {
        name: '苏州',
        value: 19
      }
      ],
      [{
        name: '盐城'
      }, {
        name: '南京',
        value: 19
      }
      ],
      [{
        name: '扬州'
      }, {
        name: '南京',
        value: 17.4
      }
      ],
      [{
        name: '镇江'
      }, {
        name: '南京',
        value: 19
      }
      ]
    ];
    // var planePath =
    //   'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z';
    var planePath = 'path://';
    var convertData = function (data) {
      var res = [];
      // for (var i = 0; i < data.length; i++) {
      //   var dataItem = data[i];
      var fromCoord = window['ALL_CITY_COORMAP'][data[0].name];
      var toCoord = window['ALL_CITY_COORMAP'][data[1].name];
      if (fromCoord && toCoord) {
        res.push([{
          coord: fromCoord,
        }, {
          coord: toCoord,
          value: data[1].value //线条颜色
        }]);
      }
      // }
      return res;
    };
    var lineWidth = function (val) {
      if ((val[1].value / 2) > 30) {
        return 6
      }
      else if ((val[1].value / 2) > 20) {
        return 5
      } else if ((val[1].value / 2) > 10) {
        return 3
      }
      else {
        return 1
      }
    }

    var lineColor = function (val) {
      if ((val[1].value / 2) > 20) {
        // return '#ff3333'
        return '#ff9933'
      } else if ((val[1].value / 2) > 10) {
        // return 'yellow'
        return '#ffcc33'
      }
      else {
        // return '#1ad746'
        return '#ffff33'//FFF68F
      }
    }

    var lineOpacity = function (val) {
      if ((val[1].value / 2) > 20) {
        return 1
      } else if ((val[1].value / 2) > 10) {
        return 0.5
      }
      else {
        return 0.3
      }
    }
    var series = [];
    data1.forEach(function (item, i) {
      series.push({
        name: '1',
        type: 'lines',
        coordinateSystem: 'arcgis',
        zlevel: 2,
        effect: {
          show: true,
          period: 2, //箭头指向速度，值越小速度越快
          trailLength: 0.01, //特效尾迹长度[0,1]值越大，尾迹越长重
          // symbol: 'arrow', //箭头图标
          symbolSize: lineWidth(item) * 2, //图标大小
        },
        lineStyle: {
          normal: {
            width: lineWidth(item),
            curveness: 0.2, //弧线角度
            opacity: lineOpacity(item),
            // color: 'yellow'
            color: lineColor(item)
          }
        },
        data: convertData(item)
      },
        {
          type: 'effectScatter',
          coordinateSystem: 'arcgis',
          zlevel: 2,
          //波纹效果
          rippleEffect: {
            period: 2,
            brushType: 'stroke',
            scale: 3
          },
          label: {
            normal: {
              show: false,
              position: 'right',
              formatter: '{b}',
              color: 'yellow'
            }
          },
          //终点形象
          symbol: 'circle',
          //圆点大小
          symbolSize: function (val) {
            return val[2] / 6;
            // 0
          },
          itemStyle: {
            normal: {
              show: false,
              color: 'yellow'
            }
          },
          data: [item].map(function (item) {
            return {
              name: item[1].name,
              value: window['ALL_CITY_COORMAP'][item[1].name].concat([item[1].value])
            };
          })
        }
      );
    });
    window['Echarts4Layer'] = new Echarts4Layer(window['CSJ_SCENE_VIEW'], echarts);
    var option = {
      series: series
    };
    window['Echarts4Layer'].setChartOption(option);
  });
}

export function openHeatmapLayer(dataArray, that) {
  that.setState({
    showDataChart: false,
  });
  loadModules(['userPlugins/HeatMapLayer'], {
    url: ARCGIS_JS_API_URL,
    dojoConfig: {
      async: true,
      packages: [
        {
          name: 'userPlugins',
          location: ARCGIS_RELATED_PLUGINS_URL,
        },
      ],
    },
  }).then(([HeatMapLayer]) => {
    var config = {
      container: document.getElementById("map"),
      radius: 30,
      maxOpacity: .8,
      minOpacity: 0,
      blur: .7,
      gradient: {
        // 0.25: "rgb(000,000,255)",
        // 0.55: "rgb(000,255,255)",
        // 0.65: "rgb(000,255,000)",
        // 0.98: "rgb(255,255,000)",
        // 1.00: "rgb(255,000,000)"
        0: "rgb(0,0,0)",
        0.3: "rgb(0,0,255)",
        0.8: "rgb(0,255,0)",
        0.98: "rgb(255,255,0)",
        1: "rgb(255,0,0)"
      }
    };
    window['HeatmapLayer'] = new HeatMapLayer(
      window['CSJ_SCENE_VIEW'],
      config,
      dataArray,
      h337
    );
    window['HeatmapLayer'].addData();
  });
}

export function openClusterLayer(parentItem, item) {
  const options = {
    url: ARCGIS_JS_API_URL,
    dojoConfig: {
      async: true,
      tlmSiblingOfDojo: false,
      packages: [
        {
          name: 'userPlugins',
          location: location.pathname.replace(/\/[^/]+$/, '') + 'userPlugins',
        },
      ],
      has: {
        'esri-promise-compatibility': 1, // enable native promises and remove the warning about using when() instead of then(). https://developers.arcgis.com/javascript/latest/guide/release-notes/index.html#improved-compatibility-with-javascript-promises
      },
    },
  };
  loadModules(['userPlugins/FlareClusterLayer_v4'], options).then(([fcl]) => {
    const subjectId = item.id;
    if (!window[subjectId]) {
      // TODO: 需后台支持
      let jsonData = dataPOI;
      const defaultSym = new SimpleMarkerSymbol({
        size: 6,
        color: '#FF0000',
        outline: null,
      });
      const renderer = new ClassBreaksRenderer({
        defaultSymbol: defaultSym,
      });
      renderer.field = 'clusterCount';
      const smSymbol = new SimpleMarkerSymbol({
        size: 22,
        outline: new SimpleLineSymbol({ color: [200, 52, 59, 0.8] }),
        color: [250, 65, 74, 0.8],
      });
      const mdSymbol = new SimpleMarkerSymbol({
        size: 24,
        outline: new SimpleLineSymbol({ color: [200, 52, 59, 0.8] }),
        color: [250, 65, 74, 0.8],
      });
      const lgSymbol = new SimpleMarkerSymbol({
        size: 28,
        outline: new SimpleLineSymbol({ color: [200, 52, 59, 0.8] }),
        color: [250, 65, 74, 0.8],
      });
      const xlSymbol = new SimpleMarkerSymbol({
        size: 32,
        outline: new SimpleLineSymbol({ color: [200, 52, 59, 0.8] }),
        color: [250, 65, 74, 0.8],
      });
      renderer.addClassBreakInfo(0, 19, smSymbol);
      renderer.addClassBreakInfo(20, 150, mdSymbol);
      renderer.addClassBreakInfo(151, 1000, lgSymbol);
      renderer.addClassBreakInfo(1001, Infinity, xlSymbol);
      const popupTemplate = new PopupTemplate({
        title: '{name}',
        content: [
          {
            type: 'fields',
            fieldInfos: [
              { fieldName: 'name', label: 'name', visible: true },
              { fieldName: 'address', label: 'address', visible: true },
              { fieldName: 'type', label: 'type', visible: true },
            ],
          },
        ],
      });
      const options = {
        id: 'flare-cluster-layer',
        clusterRenderer: renderer,
        displayFlares: false,
        clusterToScale: 2000,
        // areaRenderer: areaRenderer,
        // flareRenderer: flareRenderer,
        singlePopupTemplate: popupTemplate,
        spatialReference: new SpatialReference({ wkid: 4326 }),
        // subTypeFlareProperty: "type",
        // singleFlareTooltipProperty: "name",
        // displaySubTypeFlares: false,
        maxSingleFlareCount: maxSingleFlareCount,
        clusterRatio: 200,
        // clusterAreaDisplay: areaDisplayMode,
        data: jsonData,
      };
      window[subjectId] = new fcl.FlareClusterLayer(options);
      window['CSJ_MAP'].add(window[subjectId]);
      // enableHighlightOnPointerMove
      // 加入到当前图层列表库里
    } else {
      // 打开所有列表库里的图层
    }
  });
}

export function openServiceLayer(selectedServiceDataList, that) {
  let currentShowServiceLayers = [];
  closeAllServiceLayers();
  if (selectedServiceDataList.length > 0) {
    let currentSubLayerArray = [];
    // window[serviceLayerName].sublayers=[];
    selectedServiceDataList.map(item => {
      const serviceLayerNames = item.config.serviceLayer;
      //增加数组存储sublayers
      serviceLayerNames.map(serviceLayerName => {
        // if (!window[serviceLayerName]) {
        //   return;
        // }
        if (item.config.definitionExpression) {
          window[serviceLayerName].definitionExpression = item.config.definitionExpression;
          if(window[serviceLayerName].sublayers){
            if(window[serviceLayerName].sublayers.items){
              if (window[serviceLayerName].sublayers.items.length > 0) {
                window[serviceLayerName].sublayers.items[0].definitionExpression = item.config.definitionExpression
              }
            }
          }
        }
        if (item.config.geometryType === 'heatmap') {
          window[serviceLayerName].renderer = item.config.renderer;
        }
        currentShowServiceLayers.push(window[serviceLayerName]);
        if (item.config.sublayers) {
          //window[serviceLayerName].sublayers=item.config.sublayers;
          item.config.sublayers.map(sublayer => {
            // let sublayersArray=window[serviceLayerName].sublayers.items;
            currentSubLayerArray.push(sublayer);
          })
          //window[serviceLayerName].sublayers.push(item.config.sublayers);
          //window[serviceLayerName].visible = true;
          if (window[serviceLayerName + '_legendLayer']) {
            //window[serviceLayerName+'_legendLayer'].sublayers=item.config.sublayers;
            window[serviceLayerName + '_legendLayer'].sublayers = currentSubLayerArray;
            //window[serviceLayerName + '_legendLayer'].sublayers = item.config.legendSublayers;
            // window[serviceLayerName + '_legendLayer'].sublayers = [{id:108}];
            //[{id:95},{id:96},{id:97}];
            currentShowServiceLayers.push(window[serviceLayerName + '_legendLayer']);
            // window[serviceLayerName + '_legendLayer'].visible = false;
            window[serviceLayerName + '_legendLayer'].visible = true;
          }
        }
        window[serviceLayerName].sublayers = currentSubLayerArray;
        window[serviceLayerName].visible = true;
        //配置identify
        // configIdentify(item);
      });
    });
    // const showSlider = item.hasTimeLine;
    //配置点击查询
    configIdentify(currentSubLayerArray);
    that.setState({
      currentShowServiceLayers: currentShowServiceLayers,
      // currentSubLayerArray:currentSubLayerArray
    });
  }
}

function configIdentify(currentSubLayerArray) {
  loadModules(["esri/tasks/IdentifyTask",
    "esri/tasks/support/IdentifyParameters"], {
    url: ARCGIS_JS_API_URL,
  }).then(([IdentifyTask, IdentifyParameters]) => {
    window['CSJ_SCENE_VIEW'].on("click", executeIdentifyTask);
    // Create identify task for the specified map service
    var identifyTask = new IdentifyTask('http://10.101.42.199:8080/arcgis/rest/services/xh/XHWebM0822/MapServer');
    var params = new IdentifyParameters();
    params.tolerance = 20;
    // layerIds subLayers 转 layerIds

    //currentSubLayerArray数组
    var layerIds = [];
    currentSubLayerArray.map(item => {
      layerIds.push(item.id)
    })
    params.layerIds = layerIds;
    params.layerOption = "top";
    params.width = window['CSJ_SCENE_VIEW'].width;
    params.height = window['CSJ_SCENE_VIEW'].height;
    // params.mapExtent = window['CSJ_SCENE_VIEW'].extent;
    function executeIdentifyTask(event) {
      params.geometry = event.mapPoint;
      params.mapExtent = window['CSJ_SCENE_VIEW'].extent;
      identifyTask
        .execute(params)
        .then(function (response) {
          var results = response.results;
          if (results.length > 0) {
            // results[0]
            var attributes = results[0].feature.attributes;
            var preStr = "<table>";
            for (var prop in attributes) {
              //console.log("obj." + prop + " = " + attributes[prop]);
              // if(!prop.matches(".*[A-Z]+.*")){
              if (prop != 'OBJECTID' && prop != 'Shape' && prop != 'FID') {
                preStr = preStr + "<tr><td width='150'><B>" + prop + "</B></td><td>" + attributes[prop] + "</td></tr>";
              }
              // }
            }
            preStr = preStr + "</table>";
            window['CSJ_SCENE_VIEW'].popup.open({
              title: results[0].layerName,
              location: event.mapPoint,
              content: preStr
            })


          }
        }, function (error) {
          console.log(error)
        })
    }
  })
}

export function openGeoJsonLayer(parentItem, item, that) {
  loadModules([
    'esri/renderers/smartMapping/creators/color',
    'esri/renderers/support/jsonUtils',
    'esri/layers/support/LabelClass',
  ]).then(([colorRendererCreator, rendererJsonUtils, LabelClass]) => {
    const levelCode = that.props.selectedDataLevel;
    const subjectId = parentItem.id,
      uniqueKey = parentItem.uniqueKey,
      subLayerId = item.id,
      hoverEnabled = item.hoverEnabled,
      valueUnit = item.unit,
      subLayerTitle = item.title,
      showDataInfo = item.hasDataInfo,
      showDataChart = item.hasChart,

      labelingInfo = LabelClass.fromJSON(item.labelingInfo),
      hasGeometryData = item.hasGeometryData ? item.hasGeometryData : false;
    // 右侧linechart图
    const { selectedAllData } = that.props;
    // barChart 和 lineChart 分开
    filterDataForLineChart(selectedAllData, uniqueKey, '', subLayerId, that);

    // referenceServiceLayer
    if (item.referenceServiceLayer) {
    }

    that.setState({
      currentOpenedJsonLayerInfo: { parentItem: parentItem, item: item },
      showDataChart: showDataChart,
      showDataInfo: showDataInfo ? true : false,
      showRightPanel: showDataChart
    });
    if (item.renderer || item.rendererJson) {
      var showRenderer = item.renderer
        ? item.renderer
        : rendererJsonUtils.fromJSON(item.rendererJson);
    } else {
      showRenderer = null;
    }
    const geometryType = item.geometryType;
    if (window[subjectId + geometryType + levelCode]) {
      // 没有showRenderer  自动生成
      if (showRenderer) {
        setGeoJsonLayerRenderer(
          subjectId,
          subLayerId,
          uniqueKey,
          geometryType,
          levelCode,
          showRenderer,
          labelingInfo,
          hoverEnabled,
          subLayerTitle,
          valueUnit,
          that
        );
      } else {
        const colorParams = {
          layer: window[subjectId + geometryType + levelCode],
          view: window['CSJ_SCENE_VIEW'],
          basemap: 'topo', //grey dark topo
          field: subLayerId,
          theme: 'high-to-low',
        };
        getRenderer(colorRendererCreator, colorParams, 'continuous').then(function (renderer) {
          showRenderer = renderer;
          setGeoJsonLayerRenderer(
            subjectId,
            subLayerId,
            uniqueKey,
            geometryType,
            levelCode,
            showRenderer,
            labelingInfo,
            hoverEnabled,
            subLayerTitle,
            valueUnit,
            that
          );
        });
      }
    } else {
      //subjectId + subLayerId获取图层配置信息
      const fieldJsonArray = parentItem.fieldJsonArray;
      const layerTitle = parentItem.title;
      const childrenHaveTimeLine = parentItem.childrenHaveTimeLine;
      drawPolygonLayerByJsonData(
        subjectId,
        subLayerId,
        uniqueKey,
        geometryType,
        hasGeometryData,
        levelCode,
        layerTitle,
        fieldJsonArray,
        showRenderer,
        labelingInfo,
        childrenHaveTimeLine,
        hoverEnabled,
        subLayerTitle,
        valueUnit,
        that
      );
    }
    const showGeoJsonLayerIds = [subjectId + geometryType + levelCode];
    that.setState({ currentShowGeoJsonLayerIds: showGeoJsonLayerIds });
  });
}



/**
 * 通过json绘制图层
 * @method drawPolygonLayerByJsonData
 * @param {string} subjectId  专题id
 * @param {string} subLayerId  子图层id 渲染字段的字段名
 * @param {string} geometryType  point/polygon
 * @param {boolean} hasGeometryData  jsondata数据中是否有点位位置，与行政区相关的为false，港口机场等数据为true
 * @param {string} levelCode 当前图层的显示级别
 * @param {string} layerTitle  图层名称 显示在legend中的一级标题
 * @param {string} fieldJsonArray  生成图层字段名称
 * @param {Object} showRenderer  初始化renderer
 * @param {Array}  labelingInfo  注记 可以为空
 * @param {boolean} childrenHaveTimeLine 是否带有时间轴
 * @param {boolean} hoverEnabled 是否可以HOVER
 * @param {string}  subLayerTitle popup中显示的字段名称
 * @param {boolean} valueUnit popup中显示的单位
 */
function drawPolygonLayerByJsonData(
  subjectId,
  subLayerId,
  uniqueKey,
  geometryType,
  hasGeometryData,
  levelCode,
  layerTitle,
  fieldJsonArray,
  showRenderer,
  labelingInfo,
  hoverEnabled,
  subLayerTitle,
  valueUnit,
  that
) {
  loadModules([
    'esri/Graphic',
    'esri/geometry/Point',
    'esri/geometry/Polygon',
    'esri/layers/FeatureLayer',
    'esri/renderers/smartMapping/creators/color',
    'esri/core/promiseUtils',
  ]).then(([Graphic, Point, Polygon, FeatureLayer, colorRendererCreator, promiseUtils]) => {
    let jsonFeatureLayer;
    var jsonData = that.props.selectedData;
    function createGraphics(jsonData) {
      const graphicsPromise = promiseUtils.create(function (resolve, reject) {
        // 增加非行政区位置的数据接入 利用
        if (hasGeometryData) {
          var graphics = jsonData.map((item, index) => {
            // 约定好字段 x y
            let graphicAttributes = Object.assign({}, item);
            const graphic = new Graphic({
              geometry: new Point(item.codX, item.codY),
              attributes: graphicAttributes,
            });
            return graphic;
          });
        } else {
          var drawGraphics;
          if (geometryType === 'polygon') {
            if (levelCode === '640100') {
              drawGraphics = window['ALL_CITY_POLYGON_GRAPHICS'];
            } else {
              drawGraphics = window['ALL_PROVINCE_POLYGON_GRAPHICS'];
            }
          } else if (geometryType === 'point') {
            if (levelCode === '640100') {
              drawGraphics = window['ALL_CITY_POINT_GRAPHICS'];
            } else {
              drawGraphics = window['ALL_PROVINCE_POINT_GRAPHICS'];
            }
          }
          var graphics = drawGraphics.map((graphicItem, index) => {
            var attributeItem =
              jsonData !== null
                ? jsonData.filter(item => graphicItem.attributes.gb === item.regionCode.toString())
                : [];
            let graphicAttributes = Object.assign({}, attributeItem[0]);
            if (attributeItem.length > 0) {
              graphicAttributes['OBJECTID'] = index;
              const graphic = new Graphic({
                geometry: graphicItem.geometry,
                attributes: graphicAttributes,
              });
              return graphic;
            }
          });
        }
        resolve(graphics);
      });
      return graphicsPromise;
    }
    function createLayer(graphics) {
      // save graphics for update
      // if (childrenHaveTimeLine) {
      // TODO:可将Graphics保存用于属性更新 也可通过layer直接查询得到全部Graphics 需比较效率
      // 保证非空
      const notNullGraphics = graphics.filter(graphic => graphic);
      window[subjectId + geometryType + levelCode + 'GRAPHICS'] = notNullGraphics;
      // }
      jsonFeatureLayer = new FeatureLayer({
        source: notNullGraphics,
        title: layerTitle,
        objectIdField: 'OBJECTID',
        opacity: 0.8,
        fields: fieldJsonArray,
        renderer: showRenderer ? showRenderer : null,
        labelingInfo: labelingInfo ? [labelingInfo] : [],
        listMode: 'hide',
      });
      return jsonFeatureLayer.load();
    }
    createGraphics(jsonData)
      .then(createLayer)
      .then(function () {
        if (showRenderer) {
          window[subjectId + geometryType + levelCode] = jsonFeatureLayer;
          window['CSJ_MAP'].add(window[subjectId + geometryType + levelCode]);
          if (hoverEnabled) {
            enableHighlightOnPointerMove(
              window[subjectId + geometryType + levelCode],
              subLayerId,
              subLayerTitle,
              uniqueKey,
              valueUnit,
              that
            );
          }
          // save for colseAllLayers
          window['CREATED_GEOJSON_LAYER_IDS'].push(subjectId + geometryType + levelCode);
        } else {
          const colorParams = {
            layer: jsonFeatureLayer,
            view: window['CSJ_SCENE_VIEW'],
            basemap: 'topo', //grey dark topo
            field: subLayerId,
            theme: 'high-to-low',
            // legendOptions: {
            //   title: '户籍人口',
            // },
          };
          that
            .getRenderer(colorRendererCreator, colorParams, 'continuous')
            .then(function (renderer) {
              jsonFeatureLayer.renderer = renderer;
              window[subjectId + geometryType + levelCode] = jsonFeatureLayer;
              window['CSJ_MAP'].add(window[subjectId + geometryType + levelCode]);
              if (hoverEnabled) {
                enableHighlightOnPointerMove(
                  window[subjectId + geometryType + levelCode],
                  subLayerId,
                  subLayerTitle,
                  uniqueKey,
                  valueUnit,
                  that
                );
              }
              // save for colseAllLayers
              window['CREATED_GEOJSON_LAYER_IDS'].push(subjectId + geometryType + levelCode);
            })
            .catch(function (error) {
              console.log('error: ', error);
            });
        }
      });
  });
}

function setGeoJsonLayerRenderer(
  subjectId,
  subLayerId,
  uniqueKey,
  geometryType,
  levelCode,
  showRenderer,
  labelingInfo,
  hoverEnabled,
  subLayerTitle,
  valueUnit,
  that
) {
  // 图层切换时 无render会变白
  window[subjectId + geometryType + levelCode].renderer = showRenderer;
  window[subjectId + geometryType + levelCode].labelingInfo = labelingInfo ? [labelingInfo] : [];
  if (hoverEnabled) {
    enableHighlightOnPointerMove(
      window[subjectId + geometryType + levelCode],
      subLayerId,
      subLayerTitle,
      uniqueKey,
      valueUnit,
      that
    );
  }
  window[subjectId + geometryType + levelCode].visible = true;
}

// 增加 uniqueKey 由于 airport等数据没有 regionCode
export function updateGeoJsonLayerData(geoJsonLayer, graphics, updatedData, uniqueKey) {
  let updateFeatures = [];
  graphics.map((graphic, index) => {
    const attributes = updatedData.filter(
      item => item[uniqueKey] === graphic.attributes[uniqueKey]
    )[0];
    Object.keys(attributes).forEach(function (name) {
      graphic.attributes[name] = attributes[name];
    });
    updateFeatures.push(graphic);
  });
  const edits = {
    updateFeatures: updateFeatures,
  };
  geoJsonLayer.applyEdits(edits).then(function (editsResult) {
    if (editsResult.updateFeatureResults.length > 0) {
      //alert('更新成功');
    }
  });
}

/**
 * 通过参数生成renderer
 * @method getRenderer
 * @param {string} renderer  rendererCreator
 * @param {string} params    参数
 * @param {string} renderType  continuous/classBreaks
 */
function getRenderer(rendererCreator, params, renderType) {
  function responseCallback(response) {
    return response.renderer;
  }
  if (renderType === 'continuous') {
    return rendererCreator.createContinuousRenderer(params).then(responseCallback);
  }
  if (renderType === 'classBreaks') {
    return rendererCreator.createClassBreaksRenderer(params).then(responseCallback);
  }
}

//通过layer图层高亮区域范围
function enableHighlightOnPointerMove(layer, fieldId, fieldTitle, uniqueKey, valueUnit, that) {
  window['CSJ_SCENE_VIEW'].whenLayerView(layer).then(function (layerView) {
    if (window['VIEW_POINTER_MOVE_EVENT']) {
      window['VIEW_POINTER_MOVE_EVENT'].remove();
    }
    window['VIEW_POINTER_MOVE_EVENT'] = window['CSJ_SCENE_VIEW'].on('pointer-move', function (
      event
    ) {
      var query = layer.createQuery();
      query.geometry = window['CSJ_SCENE_VIEW'].toMap(event); // the point location of the pointer
      query.spatialRelationship = 'intersects'; // this is the default
      query.returnGeometry = true;
      query.outFields = ['*'];
      var hoverPromise = layer.queryFeatures(query);
      hoverPromise.then(function (result) {
        const feature = result.features[0];
        const { currentHightlightID } = that.state;
        if (feature) {
          const id = feature.attributes.OBJECTID;
          if (id === currentHightlightID) {
            return;
          }
          if (highlight) {
            highlight.remove();
            highlight = null;
          }
          highlight = layerView.highlight([id]);
          // 通过uniqueKey筛选数据
          const { selectedAllData } = that.props;
          filterDataForLineChart(
            selectedAllData,
            uniqueKey,
            feature.attributes[uniqueKey].toString(),
            fieldId,
            that
          );
          // 获取 name pop gdp area
          if (feature.attributes['regionName']) {
            var cityBasicInfo = city_basic_info.find(item => item.region_name === feature.attributes['regionName']);
            var radarChartData = city_relation_radardata.find(item => item.city === feature.attributes['regionName']);
            if (cityBasicInfo) {
              const currentOverviewCityName = feature.attributes['regionName'],
                currentOverviewPopVal = cityBasicInfo['total_pop'].split(".")[0],
                currentOverviewAreaVal = cityBasicInfo['total_area'].split(".")[0],
                currentOverviewGDPVal = cityBasicInfo['total_gdp'].split(".")[0];
              that.setState({
                currentHightlightID: id,
                currentOverviewCityName: currentOverviewCityName,
                currentOverviewPopVal: currentOverviewPopVal,
                currentOverviewAreaVal: currentOverviewAreaVal,
                currentOverviewGDPVal: currentOverviewGDPVal,
                currentRadarChartData: radarChartData
              });
            } else {
              window['CSJ_SCENE_VIEW'].popup.open({
                // features: [feature],
                title: feature.attributes[uniqueKey].toString(),
                updateLocationEnabled: false,
                content: !feature.attributes['timepoint']
                  ? '<b>' +
                  fieldTitle +
                  '</b>:' +
                  '&nbsp;' +
                  feature.attributes[fieldId].toFixed(1).toString() +
                  valueUnit
                  : '<b>' +
                  fieldTitle +
                  '</b>:' +
                  '&nbsp;' +
                  feature.attributes[fieldId].toFixed(1).toString() +
                  valueUnit +
                  '<br>' +
                  '<b>' +
                  '数据时点' +
                  '</b>:' +
                  '&nbsp;' +
                  feature.attributes['timepoint'],
                location:
                  feature.geometry.type === 'polygon' ? feature.geometry.centroid : feature.geometry,
              });
            }
          } else {
            that.setState({
              currentHightlightID: id,
              currentOverviewCityName: '',
              currentOverviewPopVal: '',
              currentOverviewAreaVal: '',
              currentOverviewGDPVal: '',
            });
          }
        } else {
          // 移除单个城市显示 显示整个长三角
          filterDataForLineChart(that.props.selectedAllData, uniqueKey, '', fieldId, that);

          if (window['CSJ_SCENE_VIEW'].popup.visible) {
            window['CSJ_SCENE_VIEW'].popup.close();
            window['CSJ_SCENE_VIEW'].popup.clear();
          }
          if (highlight) {
            highlight.remove();
            highlight = null;
          }
          that.setState({
            currentHightlightID: '',
            currentOverviewCityName: '',
            currentOverviewPopVal: '',
            currentOverviewAreaVal: '',
            currentOverviewGDPVal: '',
          });
        }
      });
    });
  });
}

export function closeAllGeoJsonLayers(that) {
  disableHighlightOnPointerMove();
  if (window['CSJ_SCENE_VIEW'] !== undefined && window['CSJ_SCENE_VIEW'].popup.visible) {
    window['CSJ_SCENE_VIEW'].popup.close();
    window['CSJ_SCENE_VIEW'].popup.clear();
  }
  window['CREATED_GEOJSON_LAYER_IDS'].map((item, index) => {
    window[item].visible = false;
  });
  that.setState({ currentShowGeoJsonLayerIds: [] });
}

export function closePluginLayers() {
  if (window['Echarts4Layer']) {
    window['Echarts4Layer'].setVisible(false);
  }
  if (window['HeatmapLayer']) {
    window['HeatmapLayer'].setVisible(false);
  }
}

function disableHighlightOnPointerMove() {
  if (window['VIEW_POINTER_MOVE_EVENT']) {
    window['VIEW_POINTER_MOVE_EVENT'].remove();
    window['VIEW_POINTER_MOVE_EVENT'] = null;
  }
}

function closeAllServiceLayers() {
  window['ESRI_MAP_CHILD'].closeAllOperationServiceLayers();
}

// 当前只针对统计年鉴
function filterDataForLineChart(data, uniqueKey, uniqueValue, fieldId, that) {
  // 取出年份 数据数组 value
  let timeSeries = [],
    min,
    max,
    type;
  if (uniqueValue) {
    let chartData = [];
    data
      .filter(item => item[uniqueKey] === uniqueValue)
      .map((item, index) => {
        timeSeries.push(item.statYear ? item.statYear : item.statTime);
        chartData.push(item[fieldId] ? item[fieldId].toFixed(0) : null);
        item[fieldId] > max ? (max = item[fieldId]) : null;
        item[fieldId] < min ? (min = item[fieldId]) : null;
      });
    timeSeries = timeSeries.reverse();
    chartData = chartData.reverse();
    type = 'single';
    // single代表显示单个城市的数据
    console.log(Object.assign({}, { type, uniqueValue, timeSeries, chartData }));
    that.setState({
      currentLineChartData: Object.assign({}, { type, uniqueValue, timeSeries, chartData }),
    });
  } else {
    let chartData = {},
      jiangsuArray = [],
      zhejiangArray = [],
      anhuiArray = [],
      shanghaiArray = [];
    data
      .filter(item => item['regionLevel'] === '630100')
      .map((item, index) => {
        if (item['regionName'] === '江苏') {
          timeSeries.push(item.statYear ? item.statYear : item.statTime);
          jiangsuArray.push(item[fieldId] ? item[fieldId].toFixed(0) : 0);
        } else if (item['regionName'] === '浙江') {
          zhejiangArray.push(item[fieldId] ? item[fieldId].toFixed(0) : 0);
        } else if (item['regionName'] === '安徽') {
          anhuiArray.push(item[fieldId] ? item[fieldId].toFixed(0) : 0);
        } else if (item['regionName'] === '上海') {
          shanghaiArray.push(item[fieldId] ? item[fieldId].toFixed(0) : 0);
        }
      });
    timeSeries = timeSeries.reverse();
    jiangsuArray = jiangsuArray.reverse();
    zhejiangArray = zhejiangArray.reverse();
    anhuiArray = anhuiArray.reverse();
    shanghaiArray = shanghaiArray.reverse();
    type = 'all';
    chartData = Object.assign({}, { jiangsuArray, zhejiangArray, anhuiArray, shanghaiArray });
    if (timeSeries.length > 0) {
      that.setState({
        currentLineChartData: Object.assign({}, { type, uniqueValue, timeSeries, chartData }),
      });
    } else {
      that.setState({
        currentLineChartData: null,
      });
    }
    console.log(Object.assign({}, { type, uniqueValue, timeSeries, chartData }));
  }
}

export function locateToPoi(value, that) {
  loadModules(['esri/Graphic', 'esri/symbols/TextSymbol'], {
    url: ARCGIS_JS_API_URL,
  }).then(([Graphic, TextSymbol]) => {
    const { currentPoiInfo } = that.props;
    window['GRAPHIC_LAYER_LOCATE'].graphics.removeAll();
    if (!currentPoiInfo) {
      return;
    }
    if (currentPoiInfo.length > 0) {
      const locatePoiInfo = currentPoiInfo.find(item => item.name === value);
      if (!locatePoiInfo) {
        return;
      }
      if (locatePoiInfo['displayX'] && locatePoiInfo['displayY']) {
        window['CSJ_SCENE_VIEW'].goTo({
          center: [parseFloat(locatePoiInfo['displayX']), parseFloat(locatePoiInfo['displayY'])],
          zoom: 17,
          // heading: 0,
          // tilt: 0,
        });

        var textSymbol = {
          type: 'text', // autocasts as new TextSymbol()
          color: 'white',
          haloColor: 'black',
          haloSize: '1px',
          text: locatePoiInfo['name'],
          xoffset: 3,
          yoffset: 300,
          font: {
            // autocast as new Font()
            size: 12,
            weight: 'bold',
          },
        };
        // var locateSymbol = {
        //   type: 'simple-marker', // autocasts as new SimpleMarkerSymbol()
        //   size: 10,
        //   color: [24, 141, 240],
        // };
        var locateSymbol = {
          type: "point-3d", // autocasts as new PointSymbol3D()
          symbolLayers: [{
            type: "object", // autocasts as new ObjectSymbol3DLayer()
            width: '25px',
            resource: {
              primitive: "sphere"
            },
            material: {
              color: [255, 0, 0]
            }
          }],
          verticalOffset: {
            screenLength: 40,
            maxWorldLength: 200,
            minWorldLength: 35
          },
          callout: {
            type: "line", // autocasts as new LineCallout3D()
            color: "white",
            size: 2,
            border: {
              color: 'black'
            }
          }
        };

        var locateGraphic = new Graphic({
          geometry: {
            type: 'point', // autocasts as new Point()
            longitude: parseFloat(locatePoiInfo['displayX']),
            latitude: parseFloat(locatePoiInfo['displayY']),
          },
          symbol: locateSymbol,
        });
        var textGraphic = new Graphic({
          geometry: {
            type: 'point', // autocasts as new Point()
            longitude: parseFloat(locatePoiInfo['displayX']),
            latitude: parseFloat(locatePoiInfo['displayY']),
          },
          // symbol: symbol,
          symbol: textSymbol
        });
        window['GRAPHIC_LAYER_LOCATE'].graphics.add(locateGraphic);
        setTimeout(function () {
          window['GRAPHIC_LAYER_LOCATE'].graphics.removeAll();
        }, 40000);
      }
    }
  });
}


//标准地图模块扩展 chrli 20191119
//徐汇相关接口函数均加上Xh
export function openGeoJsonLayerXh(params, that) {
  const mode = params.mode,
    name = params.name;
  if (mode == "delete") {
    if (window[name] == undefined)
      return;
    window[name] = undefined;
    window['CSJ_MAP'].remove(window['CSJ_MAP'].findLayerById(name));
    //移除
    arrayRemoveItem(window['CREATED_GEOJSON_LAYER_IDS'], name)
  }
  else if (mode == "replace") {
    if (window[name] !== undefined) {
      //setGeoJsonLayerRenderer
      window[name] = undefined;
      window['CSJ_MAP'].remove(window['CSJ_MAP'].findLayerById(name));
      //移除
      arrayRemoveItem(window['CREATED_GEOJSON_LAYER_IDS'], name)
      drawPolygonLayerByJsonDataXh(params, that);
    } else {
      drawPolygonLayerByJsonDataXh(params, that);
    }
  } else if (mode == "add") {
    if (window[name] !== undefined) {
      window[name].visible = true;
    } else {
      drawPolygonLayerByJsonDataXh(params, that);
    }
  }
}

function arrayRemoveItem(arr, val) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == val) {
      arr.splice(i, 1)
      break;
    }
  }
}

function drawPolygonLayerByJsonDataXh(
  params,
  that
) {
  loadModules([
    'esri/Graphic',
    'esri/geometry/Point',
    'esri/geometry/Polygon',
    'esri/layers/FeatureLayer',
    'esri/geometry/SpatialReference',
    'esri/layers/support/LabelClass',
    'esri/renderers/smartMapping/creators/color',
    'esri/core/promiseUtils',
  ]).then(([Graphic, Point, Polygon, FeatureLayer, SpatialReference, LabelClass, colorRendererCreator, promiseUtils]) => {
    const jsonData = params.dataArray,
      name = params.name,
      fieldJsonArray = params.fieldJsonArray,
      popupEnabled = params.popupEnabled,
      legendVisible = params.legendVisible,
      geometryType = params.type,
      showRenderer = params.renderer,
      labelingInfo = LabelClass.fromJSON(params.labelingInfo);

    function createGraphics(jsonData) {
      const graphicsPromise = promiseUtils.create(function (resolve, reject) {
        // 增加非行政区位置的数据接入 利用
        if (geometryType === 'point') {
          var graphics = jsonData.map((item, index) => {
            // 约定好字段 x y
            let graphicAttributes = Object.assign({}, item);
            const graphic = new Graphic({
              geometry: new Point({
                x: item.codX,
                y: item.codY,
                spatialReference: SpatialReference.WebMercator
              }),
              attributes: graphicAttributes,
            });
            return graphic;
          });
        }
        resolve(graphics);
      });
      return graphicsPromise;
    }
    function createLayer(graphics) {
      // save graphics for update
      // if (childrenHaveTimeLine) {
      // TODO:可将Graphics保存用于属性更新 也可通过layer直接查询得到全部Graphics 需比较效率
      // 保证非空
      const notNullGraphics = graphics.filter(graphic => graphic);
      window[name + 'GRAPHICS'] = notNullGraphics;
      // }
      window[name] = new FeatureLayer({
        source: notNullGraphics,
        id: name,
        title: name,
        objectIdField: 'OBJECTID',
        opacity: 0.8,
        fields: fieldJsonArray,
        renderer: showRenderer ? showRenderer : null,
        labelingInfo: labelingInfo ? [labelingInfo] : [],
        listMode: 'hide',
        popupEnabled: popupEnabled,
        legendVisible: legendVisible
      });
      return window[name].load();
    }
    createGraphics(jsonData)
      .then(createLayer)
      .then(function () {
        if (showRenderer) {
          window['CSJ_MAP'].add(window[name]);
          // save for colseAllLayers
          window['CREATED_GEOJSON_LAYER_IDS'].push(name);
        }
      });
  });
}

export function goToPositonXh(params) {
  window['CSJ_SCENE_VIEW'].goTo(params);
}

export function setLayerVisibleXh(params) {
  const layerName = params.layerName,
    visible = params.visible,
    sublayers=params.sublayers;
  // name: "上水管线", visible:true,
  // if (window['ALL_LAYER'] !== undefined && window['ALL_LAYER'].length > 0) {
  //   window['ALL_LAYER'].map(item => {
  //      if(item.id==layerName){
  //        item.visible=visible;
  //      }
  //   })}
  if (window[layerName]) {
    window[layerName].sulayers=sublayers
    window[layerName].visible = visible;
  }

}

export function resetMapXh(params) {
  window['ESRI_MAP_CHILD'].closeAllOperationServiceLayers();
}

